package com.nb.protocol.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @function:
 * @author: hjw
 * @date: 2018/1/7
 * @company: Sinoregal
 * @copyright: 2018 www.sinoregal.cn. All rights reserved.
 */
public class DbCtrl {
    private static final Logger logger = Logger.getLogger(DbCtrl.class);
    private static DruidDataSource dataSource;

    public static Connection getConnection() throws SQLException {
        Connection connection = null;
        logger.info("开始获取数据库连接");
        connection =  dataSource.getConnection();
        logger.info("获取数据库连接结束");
        return connection;
    }

    public static void close(Connection conn) throws SQLException
    {
        if (conn != null && !conn.isClosed())
        {
            conn.close();
        }
    }

    public static void close(Connection conn, PreparedStatement pstmt)
            throws SQLException
    {
        if (pstmt != null) {
            pstmt.close();
        }

        DbCtrl.close(conn);
    }

    public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs)
            throws SQLException
    {
        if (rs != null) {
            rs.close();
        }
        if (pstmt != null) {
            pstmt.close();
        }

        DbCtrl.close(conn);
    }



    public static void init() {
        Properties p = new Properties();
        InputStream in = DbCtrl.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            p.load(in);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(p);
            dataSource.init();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


}
